<template>
    <TopNav />

    <div class="main_wrap" style="background-color: #f5f5f5;padding: 0;">
        <div class="top">

            <el-descriptions size="large" title="" :column="2">
                <el-descriptions-item label="调拨单号：">{{ row.allocationNumber }}</el-descriptions-item>
                <el-descriptions-item label="调拨日期：">{{ row.createTime }}</el-descriptions-item>
                <el-descriptions-item label="调出店铺：">{{ row.outShopName }}</el-descriptions-item>
                <el-descriptions-item label="调入店铺：">{{ row.enterShopName }}</el-descriptions-item>
                <el-descriptions-item label="调拨人员：">{{ row.creatorName }}</el-descriptions-item>
            </el-descriptions>

        </div>
        <div class="table_wrap" ref="myTableRef">
            <!-- :header-cell-style="{ backgroundColor: 'var(--ev-c-black)', color: '#fff' }" -->
            <el-table show-overflow-tooltip :header-cell-style="{ backgroundColor: 'var(--el-color-primary)', color: '#fff' }" stripe
                :data="currentPageTableData" @current-change="handleCurrentChange" highlight-current-row
                class-name="my_table">
                <el-table-column type="index" :index="indexMethod" width="50" />
                <el-table-column prop="goodsID" label="商品编码" min-width="108" />
                <el-table-column prop="goodsName" label="商品名称" min-width="108" />
                <el-table-column prop="saleUnit" label="销售单位" min-width="108" />
                <el-table-column prop="allocateQuantity" label="数/重量" min-width="108" />
            </el-table>
        </div>

        <div class="bottom_btns">

            <el-button size="large" type="primary" @click="prev" :disabled="currentPage == 1">上一页</el-button>

            <el-button size="large" type="primary" @click="next"
                :disabled="currentPage >= Math.ceil(total / pageSize)">下一页</el-button>
            <!--调出 并且 状态为1 待接收-->
            <template v-if="row.transferType === 1 && row.status === 1">
                <el-button size="large" type="warning" @click="withDraw">撤回调拨</el-button>
                <el-button size="large" type="success" @click="printTicket">打印小票</el-button>
            </template>


            <!--调入（0或2） 并且 状态为1 待接收-->
            <template v-if="(row.transferType === 0 || row.transferType === 2) && row.status === 1">
                <el-button size="large" type="danger" @click="back">退回调拨</el-button>
                <el-button size="large" type="primary" @click="receive">接收调拨</el-button>
            </template>
        </div>

            <!--打印wrap-->
            <div ref="domDiv" class="print_wrap" >
            <div class="title">调拨单[一手店]</div>
            <div>单号：{{ row.allocationNumber }}</div>
            <div>调出店铺：{{ row.outShopName  }}</div>
            <div>调入店铺：{{row.enterShopName  }}</div>
            <div>创建人：{{ row.creatorName }}</div>
            <div>时间：{{ row.createTime }}</div>
            <div class="line"></div>
            <div class="flex">
                <div>商品/数(重)量</div>
                <div>单位</div>
            </div>
            <div class="item" v-for="item in pageTableData.flat()" :key="item.goodsID">
                <div>{{ item.goodsName }}</div>
                <div class="flex">
                    <div>{{ item.allocateQuantity }}</div>
                    <div>{{ item.saleUnit }}</div>
                </div>
            </div>
            <div class="line"></div>
            <div class="flex">
                <div>件数合计</div>
                <div>{{ totalQuantity }}</div>
            </div>
           
            <div class="margin_bottom_placeholder"></div>
        </div>
    </div>


</template>

<script setup lang='ts'>
// @ts-nocheck
import pinyin from "pinyin";
import domtoimage from 'dom-to-image'; //dom转图片
import { ElMessage } from 'element-plus'
import { getDateTimeString } from '@renderer/utils'
import { ref, onMounted, watch, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@renderer/store/user'
import { useRoute, useRouter } from "vue-router";
import { getTransferDesc, backOrder, receiveOrder, withDrawOrder } from '@renderer/api/transferdesc'
const router = useRouter()
const route = useRoute()
const row = ref(JSON.parse(route.query.row))
console.log(row)
const id = row.value.id
const pageTableData = ref([]) //分页后的数据
const userStore = useUserStore()
const { userInfo, shopInfo } = storeToRefs(userStore)
const shopID = shopInfo.value.shopID
const saleOrganizationID = userInfo.value.user_organizationId


const tableData = ref([])
function handleCurrentChange() {

}
const pageSize = ref(1)
const myTableRef = ref()
const currentPage = ref(1)
const total = ref(0)
const domDiv = ref(null)

onMounted(async () => {
    let tableHeight = myTableRef.value.offsetHeight
    let singleRowHeight = 40 //每行高度
    pageSize.value = Math.floor(tableHeight / singleRowHeight) - 1 //每页最多显示行数(-1 是减去header)

    try {
        const { data } = await getTransferDesc(saleOrganizationID, id, shopID)
    tableData.value = data
    total.value = data.length
    pageTableData.value = paginateData(data, pageSize.value) 
    } catch (error) {
        console.log(error)
    }

    
})

function prev() {
    if (currentPage.value <= 1) return
    currentPage.value--
}
function next() {
    if (currentPage.value >= pageTableData.value.length) return
    currentPage.value++
}

//当前页数据
const currentPageTableData = computed(() => {
    return pageTableData.value[currentPage.value - 1]
})

const totalQuantity = computed(()=>{
        let total = 0
        const data = pageTableData.value.flat()
        for (let i = 0; i < data.length; i++) {
            if (data[i].isQuantityUnit === 1) {
                total += data[i].allocateQuantity * 1
            } else {
                total += 1
            }
        }
        return total
})

//分页
function paginateData(data, pageSize) {
    const pages = [];
    for (let i = 0; i < data.length; i += pageSize) {
        pages.push(data.slice(i, i + pageSize));
    }
    return pages;
}
//计算序号
function indexMethod(index) {
    return (currentPage.value - 1) * pageSize.value + index + 1
}

//接收
async function receive() {
    const receiveAllocationDto = {
        shopAllocationID: id,
        saleOrganizationID,
        outShopID: row.value.outShopID,
        enterShopID: row.value.enterShopID,
        outShopName: row.value.outShopName,
        enterShopName: row.value.enterShopName,
        receiveGoodsDtos: tableData.value
    }
    try {
        const { msg } = await receiveOrder(receiveAllocationDto)
    ElMessage({
        message: msg,
        type: 'success',
    })
    router.back()
    } catch (error) {
        console.log(error)
    }

}

//退回
async function back() {
    try {
        const { msg } = await backOrder(saleOrganizationID,id)
    ElMessage({
        message: msg,
        type: 'success',
    })
    router.back()
    } catch (error) {
        console.log(error)
    }

}

//撤回
async function withDraw() {
    try {
        const { msg } = await withDrawOrder(saleOrganizationID,id)
    ElMessage({
        message: msg,
        type: 'success',
    })
    router.back()
    } catch (error) {
        console.log(error)
    }

}

//打印小票
async function printTicket(){
    console.log(domDiv.value)
    getDomToImg(domDiv.value)
}
//dom-to-image
function getDomToImg(node,) {
    domtoimage.toPng(node,)
        .then(function (dataUrl) {
            console.log(dataUrl)
            const base64ImageData = dataUrl.replace(/^data:image\/png;base64,/, '');
            window.electron.ipcRenderer.send('base64ImageData', { data: base64ImageData })
        })
        .catch(function (error) {
            console.error('oops, something went wrong!', error);
        });
}
</script>
<style lang='scss' scoped>
.custom_select {

    .el-select-dropdown__item {

        line-height: 50px;
        height: 50px;

    }
}
</style>
<style lang='scss' scoped>
.main_wrap{
    position: relative;
    overflow: hidden;
}

.top {
    padding: 10px;
    background-color: #fff;

    .row {
        display: flex;
        align-items: center;


        .form_item {
            display: flex;
            align-items: center;
            margin-right: 10px;

            .label {
                width: 80px;

            }
        }

    }
}

.table_wrap {
    padding: 0 10px;
    height: calc(100% - 120px - 50px);
}

.bottom_btns {
    position: absolute;
    bottom: 5px;
    left: 10px;
}

.shop_list {
    padding: 10px 0;
}



//打印相关
.print_wrap {
    .title {
        text-align: center;
        line-height: 1.5;
        font-size: 38px;
    }

    background-color: #fff;
    color: #000;
    width: 600px; //这里一定设置为600px 经过测试后的合适距离
    padding: 10px 10px 10px 0px; //注意这里左边距 不设置，使用的是config.ini中的值
    box-sizing:border-box;
    // font-weight: bold;
    font-size:36px;
    position: absolute;
    top: 0;
    left:0;
    z-index: -10;

    .line {
        width: 100%;
        border-top: 1px dashed #000;
        height: 1px;
        margin: 15px 0;
    }

    .margin_bottom_placeholder {
        //这里使用空div 站位 下边距
        width: 100%;
        height: 300px;
        
    }

    .flex {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>